package com.zlyx.easy.asyn.supports;

import java.util.Collection;

import org.springframework.beans.factory.InitializingBean;

import com.zlyx.easy.asyn.annotations.MsgCustomer;
import com.zlyx.easy.asyn.interfaces.AsynMsgCustomer;
import com.zlyx.easy.asyn.model.AsynMessage;
import com.zlyx.easy.core.map.MultiMap;
import com.zlyx.easy.core.spring.RepeatedBean;
import com.zlyx.easy.core.utils.EnvUtils;
import com.zlyx.easy.core.utils.JsonUtils;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * @Auth 赵光
 * @Describle
 * @2019年9月7日
 */
public abstract class AbstractMsgListener extends RepeatedBean<AsynMsgCustomer<?>> implements InitializingBean {

	private MultiMap<AsynMsgCustomer<?>> beansMap = MultiMap.newMap();

	/**
	 * 广播消息
	 * 
	 * @param msg
	 */
	protected void handleMsg(String msg) {
		if (StringUtils.isNotEmpty(msg)) {
			try {
				AsynMessage asynMessage = JsonUtils.fromJson(msg, AsynMessage.class);
				handleMsg(asynMessage.getChannel(), asynMessage.getMsg());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected void handleMsg(String channel, Object msg) throws Exception {
		if (ObjectUtils.isNotEmpty(msg)) {
			Collection<AsynMsgCustomer<?>> listeners = beansMap.get(channel);
			if (ObjectUtils.isNotEmpty(listeners)) {
				for (AsynMsgCustomer listener : listeners) {
					listener.subscribe(channel, JsonUtils.fromJson(msg, listener.getTClass()));
				}
			}
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (beans != null) {
			for (AsynMsgCustomer<?> listener : beans) {
				if (listener.getClass().isAnnotationPresent(MsgCustomer.class)) {
					String[] channels = listener.getClass().getAnnotation(MsgCustomer.class).channels();
					if (channels != null && channels.length > 0) {
						for (String channel : channels) {
							beansMap.addValues(EnvUtils.getProperty(channel), listener);
						}
					}
				}
			}
		}
		logger.info("异步消息监听池：{}", beans);
	}
}
